package cn.itcast.job;

import cn.itcast.service.OrderService;
import cn.itcast.zookeeper.annotation.ElasticSimpleJob;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
// @Component
@ElasticSimpleJob(
        jobName = "orderSummarySimpleJob",
        corn = "0/10 * * * * ?",
        shardingTotalCount = 24,
        overwrite = true)
public class OrderSummarySimpleJob implements SimpleJob {
    @Autowired
    private OrderService orderService;
    
    @SneakyThrows
    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("第几个分片执行任务: {}", shardingContext.getShardingItem());
        //1.获取分片项
        int item = shardingContext.getShardingItem();
        
        //2.将前一天日期，拆分成24个时间段. 00 01 02 。。
        //2.1 前一天日期0点
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        
        //2020-07-18  这一天的数据
        // SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // Date date1 = format.parse("2020-07-18");
        
        //2.2 基于0点，+1小时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < 24; i++) {
            Date date = DateUtils.addHours(calendar.getTime(), i);
            // Date date = DateUtils.addHours(date1, i);
            dateList.add(date);
        }
        
        //3.每一个分片，统计一个时间段订单信息。
        //eg: 0    00 01
        //eg: 1    01 02
        //...
        Date date = dateList.get(item);
        Date endDate = DateUtils.addHours(date, 1);
        orderService.countOrder(date, endDate);
    }
}
